from typing import Any

from lxml import etree


def parse_hdr(hdr_path: str) -> dict:
    tree = etree.parse(hdr_path)
    root = tree.getroot()

    if root is None:
        return {}

    # 初始化统一结构
    data: dict[str, Any] = {
        'FaultStartTime': '',
        'FaultKeepingTime': '',
        'DeviceInfo': [],
        'TrigInfo': [],
        'FaultInfo': [],
        'TripInfo': []
    }

    if root.tag == 'FaultReport':
        for dev in root.xpath('.//DeviceInfo'):
            name = dev.findtext('name')
            value = dev.findtext('value')
            if name:
                data['DeviceInfo'].append({'name': name, 'value': value})

        for trig in root.xpath('.//TrigInfo'):
            data['TrigInfo'].append({
                'time': trig.findtext('time'),
                'name': trig.findtext('name'),
                'value': trig.findtext('value'),
                'setting': trig.findtext('setting')
            })

        for fault in root.xpath('.//FaultInfo'):
            name = fault.findtext('name')
            value = fault.findtext('value')
            unit = fault.findtext('unit')
            if name:
                data['FaultInfo'].append({
                    'name': name,
                    'value': value,
                    'unit': unit
                })

        for trip in root.xpath('.//TripInfo'):
            data['TripInfo'].append({
                'time': trip.findtext('time'),
                'name': trip.findtext('name'),
                'value': trip.findtext('value'),
                'phase': trip.findtext('phase')
            })

        f = root.find('.//FaultStartTime')
        data['FaultStartTime'] = f.text.strip() if f is not None and f.text else ''

        f = root.find('.//FaultKeepingTime')
        data['FaultKeepingTime'] = f.text.strip() if f is not None and f.text else ''

    elif root.tag == 'RecorderReport':
        fault = root.find('.//Fault')
        fault_info_items = []

        if fault is not None:
            fault_time = fault.find('.//FaultTime')
            data['FaultStartTime'] = fault_time.get('value', '') if fault_time is not None else ''

            fpt = fault.find('.//FPT')
            if fpt is not None:
                desc = fpt.get('desc', '故障类型')
                fault_info_items.append({'name': desc, 'value': fpt.get('value', '') or '未知故障类型', 'unit': None})

                phase = fpt.find('.//Phase')
                if phase is not None:
                    fault_info_items.append({
                        'name': phase.get('desc', '相别'),
                        'value': phase.get('value', '') or '未知相位',
                        'unit': None
                    })

                grounded = fault.find('.//Grounded')
                if grounded is not None:
                    fault_info_items.append({
                        'name': grounded.get('desc', '接地'),
                        'value': grounded.get('value', ''),
                        'unit': None
                    })

            for tag in ['Position', 'Range']:
                el = fault.find(f'.//{tag}')
                if el is not None:
                    fault_info_items.append({
                        'name': el.get('desc', tag),
                        'value': el.get('value', ''),
                        'unit': None
                    })

        data['FaultInfo'] = fault_info_items

    return data


if __name__ == '__main__':
    path = '../data/11.25故障录波.hdr'
    result = parse_hdr(path)

    for key, value in result.items():
        print(f'{key}: {value}')
